package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.Result;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品 包含口味dish_flavor表和菜品dish表
     * 同时还有下拉框显示菜品分类名称
     * @param dishDto
     * @return Result.success("新增菜品成功");
     */
    @PostMapping
    public Result<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        //同时操作两张表，自己写·方法
        dishService.saveWithFlavor(dishDto);

        //清理修改菜品所在分类缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return Result.success("新增菜品成功");
    }

    /**
     * 菜品信息的分页查询 其中分类名称不在dish表内，通过分类id找名称，进行对象拷贝
     * @param page
     * @param pageSize
     * @param name
     * @return Result.success(pageInfo);
     */
    @GetMapping("/page")
    public Result<Page> page(int page,int pageSize,String name){
        //分页构造器
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(name != null,Dish::getName,name);
        //排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        //执行分页查询
        dishService.page(pageInfo,queryWrapper);

        //对象拷贝
        //records字段需要单独处理,需要遍历并转换成 DishDto 对象。
        //records不拷贝是因为对应的List<Dish>集合 而集合对应就是页面展示的列表数据(需要分类名称)
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        //获得records
        List<Dish> records = pageInfo.getRecords();

        //将records处理类型
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //将普通属性（除分类名称）拷贝到dishDto对象上
            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            return dishDto;
        }).collect(Collectors.toList());
        //将转换类型后的records赋值
        dishDtoPage.setRecords(list);
        dishService.page(pageInfo,queryWrapper);
        return Result.success(pageInfo);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<DishDto> get(@PathVariable Long id){

        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return Result.success(dishDto);
    }


    /**
     * 修改菜品 包括菜品分类和口味
     * @param dishDto
     * @return Result.success("修改菜品成功");
     */
    @PutMapping
    public Result<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        dishService.updateWithFlavor(dishDto);

        //清理修改菜品所在分类缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return Result.success("修改菜品成功");
    }

    /**
     * 删除菜品
     * @param ids
     * @return Result.success("删除菜品成功");
     */
    @DeleteMapping
    public Result<String> delete(@RequestParam List<String> ids){
        log.info("删除菜品的id:{}",ids);

        //select categoryId from Dish where id in {?,?...}

        //根据id查分类id
        List<String> categoryIds = dishService.getCategoryByIds(ids);
        log.info("categoryIds ================= ：{}",categoryIds);
        String key = null;
        for (String categoryId : categoryIds) {
            //删除菜品所在分类缓存
            key = "dish_" + categoryId + "_1";
            redisTemplate.delete(key);
        }

        dishService.removeByIds(ids);


        return Result.success("删除菜品成功");
    }

    /**
     * 菜品管理页面：修改菜品的起售和停售的状态 前端已经把status反转了不需要再反转
     * @param status
     * @param ids
     * @return Result.success("菜品信息修改成功");
     */
    @PostMapping("/status/{status}")
    public Result<String> updateStatus(@PathVariable Integer status,@RequestParam List<String> ids){
        log.info("ids = {}",ids);

        List<String> categoryIds = dishService.getCategoryByIds(ids);

            log.info("categoryIds ================= ：{}",categoryIds);
            String key;
            for (String categoryId : categoryIds) {
                //删除菜品所在分类缓存
                key = "dish_" + categoryId + "_1";
                redisTemplate.delete(key);
            }


        dishService.updateStatus(ids,status);

        return Result.success("菜品信息修改成功");
    }


    /**
     * 根据条件查询对应的菜品数据：使用在套餐管理页面中新增套餐里的套餐菜品
     * @param dish
     * @return Result.success(dtoList);
     */
    @GetMapping("/list")
    public Result<List<DishDto>> list(Dish dish){
        
        List<DishDto> dtoList;
        //手动设置key
        String key = "dish_" + dish.getCategoryId() + "_1";

        //1.直接从缓存中获取
        dtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        //2.如果有就返回缓存
        if (dtoList != null){
            log.info("返回缓存前，证明返回了缓存============================");
            return Result.success(dtoList);
        }

        log.info("缓存之后，看看会不会执行=============================");

        //3.没有查数据库

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        dtoList = list.stream().map((item)->{
            Long dishId = item.getId();
            DishDto dishDto = dishService.getByIdWithFlavor(dishId);
            BeanUtils.copyProperties(item,dishDto);
            return dishDto;
        }).collect(Collectors.toList());

        log.info("dtoList:{}",dtoList);

        //查完写到缓存里，一小时过期
        redisTemplate.opsForValue().set(key,dtoList,1, TimeUnit.HOURS);


        return Result.success(dtoList);
    }
}
